<?php

namespace App\Admin\Controllers;

use App\Models\Book;
use App\Models\Classify;
use App\Models\ClassifyBook;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class ClassifyBookController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '书籍分类';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ClassifyBook);

        $grid->column('id', __('Id'));
        $grid->column('classify_id', __('分类 id'))->sortable();
        $grid->column('classify.name', __('分类 名称'));
        $grid->column('book_id', __('书籍 id'))->sortable();
        $grid->column('book.name', __('书籍名称'));
        $grid->column('sort', __('排序'))->sortable();
        $grid->column('created_at', __('创建时间'));
        //$grid->column('updated_at', __('Updated at'));

        $grid->filter(function ($filter){
            $filter->disableIdFilter();
            $filter->equal('classify_id','分类ID');
            $filter->equal('book_id','书籍ID');
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ClassifyBook::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('classify_id', __('Classify id'));
        $show->field('book_id', __('Book id'));
        $show->field('sort', __('Sort'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ClassifyBook);


        $classifyOption = [];
        $classifies = Classify::select(['id', 'name'])->get();
        foreach($classifies as $item){
            $classifyOption[$item->id] = $item->name;
        }
        $form->select('classify_id', '分类')->options($classifyOption)->rules('required');


        $bookOption = [];
        $books = Book::select(['id', 'name'])->get();
        foreach($books as $item){
            $bookOption[$item->id] = $item->name;
        }
        $form->select('book_id', '书本')->options($bookOption)->rules('required');

        $form->number('sort', __('排序'))->rules('required');

        return $form;
    }
}
